package com.wendy.file.controller;

import com.wendy.common.core.errcode.file.FileError;
import com.wendy.common.core.exception.file.FileUploadException;
import com.wendy.common.web.utils.file.FileUtils;
import com.wendy.file.domain.SysFile;
import com.wendy.file.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件请求处理
 *
 * @author wendy
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public SysFile upload(MultipartFile file) throws  FileUploadException {
            // 上传并返回访问地址
        String url = null;
        try {
            url = sysFileService.uploadFile(file);
        } catch (Exception e) {
            log.error(e.getMessage());
            FileError.FILE_UPLOAD_ERROR.fire();
        }
        SysFile sysFile = new SysFile();
        sysFile.setName(FileUtils.getName(url));
        sysFile.setUrl(url);
        return sysFile;
    }

    @PostMapping("/upload/{dir}")
    public SysFile upload(MultipartFile file, @PathVariable String dir) throws  FileUploadException {
            // 上传并返回访问地址
        String url = null;
        try {
            url = sysFileService.uploadFile(file);
        } catch (Exception e) {
            log.error(e.getMessage());
            FileError.FILE_UPLOAD_ERROR.fire();
        }
        SysFile sysFile = new SysFile();
        sysFile.setName(FileUtils.getName(url));
        sysFile.setUrl(url);
        return sysFile;
    }
}